package com.plug.common.model;

import com.plug.common.consts.Code;
import com.plug.common.utils.ValidateUtils;
import org.springframework.validation.BindingResult;

import java.util.Iterator;
import java.util.Map;

/**
 * 验证结果返回模型
 *
 * @author Archx[archx@foxmail.com]
 * @date 2016/3/21 0021
 */
public class ValidateResult extends AbstractResult {

    public ValidateResult() {
        setCode(Code.ERR_INVALID_PARAMETER);
        setMessage("Invalid Parameter");
    }

    public ValidateResult(BindingResult result) {
        this();
        setErrors(ValidateUtils.handle(result));
    }

    /**
     * 错误结果
     * <p/>
     * 字段 -> 错误信息
     */
    public Map<String, String> errors;

    public Map<String, String> getErrors() {
        return errors;
    }

    public void setErrors(Map<String, String> errors) {
        this.errors = errors;
    }

    /**
     * 获取错误消息
     *
     * @return
     */
    public String getErrorsMessage() {
        StringBuilder sb = new StringBuilder();
        if (errors != null) {
            Iterator<Map.Entry<String, String>> it = errors.entrySet().iterator();
            while (it.hasNext())
                sb.append(it.next().getValue() + "\n");
        }
        return sb.toString();
    }
}
